package com.lzhl.buildjar.util;

import com.lzhl.buildjar.exception.DaoException;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * 数据库工具类
 */
public class DbUtils {

    /**
     * 取得连接
     * @param props 连接设置
     * @return 连接
     */
    public static Connection getConnection(Properties props) {
        String driverClassName = props.getProperty("driverClassName").trim();
        String url = props.getProperty("url").trim();
        String username = props.getProperty("username").trim();
        String password = props.getProperty("password").trim();
        String autoCommit = props.getProperty("autoCommit").trim();

        try {
            Class.forName(driverClassName);
        }
        catch (ClassNotFoundException e) {
            throw new DaoException("无法加载驱动程序[" + driverClassName + "]。", e);
        }

        try{
            Connection conn;
            //指定用户名
            if(username.length() != 0) {
                conn = DriverManager.getConnection(url, username, password);
            }
            else {
                conn = DriverManager.getConnection(url);
            }
            //默认不自动提交
            conn.setAutoCommit(!"false".equalsIgnoreCase(autoCommit));

            return conn;
        }
        catch (SQLException e) {
            throw new DaoException("连接数据库发生错误。", e);
        }
    }

    public static void main(String[] args) throws Exception {
        Properties props = new Properties();
        props.setProperty("driverClassName", "org.sqlite.JDBC");
        props.setProperty("url", "jdbc:sqlite:test.db");
        props.setProperty("username", "");
        props.setProperty("password", "");
        props.setProperty("autoCommit", "false");

        Connection conn = getConnection(props);
        conn.close();
    }

}
